import { createStore } from 'vuex';
import {getCookie,setCookie} from "@/utils/common";
import {loginApi,fetchUserApi} from "@/api/webApi";

export default createStore({
    namespaced: true,
    state: () => ({
        token: localStorage.getItem('token') || '',
        userInfo: JSON.parse(localStorage.getItem('userInfo')) || null
    }),
    mutations: {
        SET_TOKEN(state, token) {
            state.token = token;
            localStorage.setItem('token', token);
        },
        SET_USERINFO(state, userInfo) {
            state.userInfo = userInfo;
            localStorage.setItem('userInfo', JSON.stringify(userInfo));
        },
        CLEAR_AUTH(state) {
            state.token = '';
            state.userInfo = null;
            localStorage.removeItem('token');
            localStorage.removeItem('userInfo');
        }
    },
    actions: {
        async login({ commit }, credentials) {
            const res = await loginApi(credentials);
            commit('SET_TOKEN', res.data.token);
            commit('SET_USERINFO', res.data.user);
            return res;
        },
        async fetchUser({commit},token){
            const res = await fetchUserApi(token);
        },
        logout({ commit }) {
            commit('CLEAR_AUTH');
        }
    },
    getters: {
        isAuthenticated: state => {
            let res = !!state.token
            console.log('debugger res:',res)
            return res
        },
        currentUser: state => state.userInfo
    }
})
// export default createStore({
//     state: {
//         count: 0,
//         user: null
//     },
//     mutations: {
//         increment(state) {
//             state.count++;
//         },
//         setUser(state, user) {
//             state.user = user;
//         }
//     },
//     actions: {
//         async fetchUser({ commit }) {
//             let token = getCookie('token')
//             console.log('token',token)
//             // const user = await api.getUser();
//             const user = null
//             commit('setUser', user);
//         }
//     },
//     getters: {
//         isLoggedIn:(state) => {
//             let token = getCookie('token')
//             let isLoggedIn = state.user != null &&token
//             console.log('isLoggedIn',isLoggedIn)
//             return isLoggedIn
//         },
//         doubleCount: (state) => state.count * 2
//     }
// });
